package top.xiaoshuaila.moments.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import top.xiaoshuaila.moments.mapper.MessageMapper;
import top.xiaoshuaila.moments.mapper.UserMapper;
import top.xiaoshuaila.moments.pojo.RespBean;
import top.xiaoshuaila.moments.pojo.Users;
import top.xiaoshuaila.moments.utils.Dateutils;
import top.xiaoshuaila.moments.utils.JwtTokenUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Override
    public RespBean login(String username, String password,
                          HttpServletRequest request) {
        UserDetails userDetails =
                userMapper.getWithName(username);
        System.out.println(userDetails);
        if(null==userDetails||!userDetails.getPassword().equals(password))
        {
            return RespBean.error("用户名或者密码不正确");
        }
        System.out.println("success");
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(userDetails
                        ,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token=jwtTokenUtil.generateToken(userDetails);
        Map<String,String> map=new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",map);
    }

    @Override
    public RespBean loginInfo (HttpServletRequest request) {
        //通过tokenHeader获取请求头里面的token
        String authHeader = request.getHeader(tokenHeader);
        /*   String authHeader = JwtTokenUtil.test;*/
        //如果为websocket的连接,则从请求参数获取链接
        if(request.getRequestURI().startsWith("/ws/"))
        authHeader=request.getParameter(tokenHeader);
        //获取正确的token
        String authToken=authHeader.substring(tokenHead.length());
        //通过jwt工具类获取token的username
        String username =
                jwtTokenUtil.getUserNameFromToken(authToken);
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        return RespBean.success("用户已登录",userDetails);
    }

    @Override
    public boolean containusername(String un) {
        return userMapper.containusername(un);
    }

    @Override
    public void regist(String un, String rn, String pw1,
                       String intro, String headphoto, Timestamp datetime) {
        userMapper.regist(un,rn,pw1,intro,headphoto,datetime);
        long id=userMapper.getId(un);
        userMapper.adminfans(id,Dateutils.getDatetime());
        messageMapper.addMessagesfocu(1,id,"用户“小帅啦”关注了您！",Dateutils.getDatetime(),1);
    }
}
